<?php

class ShopController extends Controller {

    public $layout = '//layouts/shop';

    public function init() {
        parent::init();
        //購物車初始化
        $cart = Yii::createComponent(array(
                    'class' => 'webroot.admin.protected.extensions.shoppingCart.EShoppingCart'
                ));
        $cart->init();
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'detail'),
                'users' => array('*'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('cart', 'add2cart', 'remove', 'pay', 'confrim', 'done', 'coinDiscount', 'test'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    
    //驗證用戶是否通過了驗證
    protected function check(){
        if (!Helper::userStatus(Yii::app()->user->id)) {
            header("Content-type:text/html;charset=utf-8");
            echo "<script>alert('您尚未完成驗證，還無法購物!');location.href='" . Yii::app()->createUrl('site/userInfo') . "';</script>";
            exit;
        }
    }

    //商城首頁
    public function actionIndex() {
        $pcid = (int) $_GET['cid'];
        $condition = new CDbCriteria();
        $condition->order = 'hot desc';
        if ($pcid > 0) {
            $condition->addCondition('pcid=' . $pcid);
        }
        $condition->addCondition("status='正常'");
        $rowset = Product::model()->findAll($condition);
        unset($condition);
        $condition = new CDbCriteria();
        $condition->order='hot desc';
        $condition->addCondition('class=4');
        $rowTable = Slide::model()->findAll($condition);
        unset($condition);
        $this->render('index', array(
            'rowset' => $rowset,
            'rowTable' => $rowTable,
        ));
    }

    //商品詳情頁
    public function actionDetail($pid) {
        $condition = new CDbCriteria();
        $condition->addCondition('pid=' . (int) $pid);
        $condition->addCondition("status='正常'");
        $row = Product::model()->find($condition);
        unset($condition);
        if (!$row) {
            $this->redirect(array('index'));
        }
        $this->render('detail', array(
            'row' => $row,
        ));
    }

    //購物車
    public function actionCart() {
        $this->check();
        $user = User::model()->findByPk(Yii::app()->user->id);
        $positions = Yii::app()->shoppingCart->getPositions();
//        var_dump($positions);
        $this->render('cart', array(
            'rowset' => $positions,
            'user' => $user,
        ));
    }

    //加入購物車
    public function actionAdd2cart() {
        $this->check();
        $pid = (int) $_GET['pid'];
        $num = (int) $_GET['count'];
        if($num<=0){
            $num=1;
        }
        $product = Product::model()->findByPk($pid);
        if ($product) {
            Yii::app()->shoppingCart->put($product,$num);
        }
        $this->redirect(array('cart'));
    }

    //從購物車中移除
    public function actionRemove() {
        $this->check();
        $pid = (int) $_GET['pid'];
        $product = Product::model()->findByPk($pid);
        if ($product) {
            Yii::app()->shoppingCart->remove($product->getId());
        }
        $this->redirect(array('cart'));
    }

    //支付
    public function actionPay() {
        $this->check();
        if (Yii::app()->shoppingCart->isEmpty()) {
            $this->redirect(array('cart'));
        }
        $payinfo = unserialize(Yii::app()->session->get('payinfo'));
        if (!$payinfo) {
            $payinfo = new PayForm();
            $payinfo->pre = 1;
            $payinfo->paytype = 1;
            $payinfo->receipttype = 3;
        }
        if (Yii::app()->request->isPostRequest) {
            $payinfo = new PayForm();
            $payinfo->name = $_POST['name'];
            $payinfo->pre = $_POST['pre'];
            $payinfo->phone = $_POST['phone'];
            $payinfo->email = $_POST['email'];
            $payinfo->address = $_POST['address'];
            $payinfo->paytype = $_POST['paytype'];
            $payinfo->receipttype = $_POST['receipttype'];
            $payinfo->receiptfield1_1 = $_POST['receiptfield1_1'];
            $payinfo->receiptfield1_2 = $_POST['receiptfield1_2'];
            $payinfo->receiptfield1_3 = $_POST['receiptfield1_3'];
            $payinfo->receiptfield1_4 = $_POST['receiptfield1_4'];
            $payinfo->receiptfield2 = $_POST['receiptfield2'];

            if ($payinfo->validate()) {
                Yii::app()->session->add('payinfo', serialize($payinfo));
                $this->redirect(array('confrim'));
            }
        }
        $this->render('pay', array('payinfo' => $payinfo));
    }

    //確認
    public function actionConfrim() {
        $this->check();
        $payinfo = unserialize(Yii::app()->session->get('payinfo'));

        //判斷購物金抵扣情況
        $this->checkCoin();

        if (!$payinfo || Yii::app()->shoppingCart->isEmpty()) {
            $this->redirect(array('pay'));
        }
        $positions = Yii::app()->shoppingCart->getPositions();
        $this->render('confrim', array(
            'payinfo' => $payinfo,
            'rowset' => $positions,
        ));
    }

    //下單
    public function actionDone() {
        $this->check();
        //訂單保存
        $payinfo = unserialize(Yii::app()->session->get('payinfo'));
        if (!$payinfo) {
            $this->redirect(array('pay'));
        }
        //判斷購物金抵扣情況
        $this->checkCoin();
        $user = User::model()->findByPk(Yii::app()->user->id);
        $trans = Yii::app()->db->beginTransaction();
        try {
            //訂單主記錄保存
            $order = new Order();
            $order->uid = Yii::app()->user->id;
            $order->pay_type = $payinfo->paytype;
            $order->total = Yii::app()->shoppingCart->getCost();
            $order->freight = Yii::app()->params['freight'];
            $order->coin = Yii::app()->session->get('coin');
            $order->total_final = $order->total + $order->freight - Yii::app()->session->get('coin');
            $order->consignee = $payinfo->name;
            $order->phone = $payinfo->phone;
            $order->email = $payinfo->email;
            $order->pre = $payinfo->pre;
            $order->address = $payinfo->address;
            $order->receipt_type = $payinfo->receipttype;
            $fieldStr = 'receiptfield1_' . $payinfo->receipttype;
            $order->receipt_field1 = $payinfo->$fieldStr;
            $order->receipt_field2 = $payinfo->receiptfield2;
            $positions = Yii::app()->shoppingCart->getPositions();
            $order->save();

            //訂單商品明細保存
            $positions = Yii::app()->shoppingCart->getPositions();
            foreach ($positions as $item) {
                $orderItem = new OrderItem;
                $orderItem->oid = $order->oid;
                $orderItem->pid = $item->pid;
                $orderItem->price = $item->price;
                $orderItem->number = $item->getQuantity();
                $orderItem->hongyun = $item->hongyun;
                $orderItem->coin = $item->coin;
                $orderItem->save();
                $order->hongyun_return += $item->hongyun * $item->getQuantity();
                $order->coin_return += $item->coin * $item->getQuantity();
            }

            //保存訂單的返點和返金幣
            $order->save();

            if ($order->coin > 0) {
                //從用戶購物金餘額中扣除金幣
                $user->coin = $user->coin - Yii::app()->session->get('coin');
                $user->save();

                //保存coin flow記錄
                $record = new CoinFlow();
                $record->uid = $user->uid;
                $record->type = 1;
                $record->amount = Yii::app()->session->get('coin');
                $record->flow_type = 2;
                $record->description = '訂單（' . $order->oid . '）從餘額扣取購物金。';
                $record->save();
            }

            //提交
            $trans->commit();
        } catch (Exception $e) {
            $trans->rollback();
//            echo $e->getMessage();
//            $this->response(array('status' => 1, 'msg' => $e->getMessage()));
        }
        header("Content-type: text/html; charset=utf-8"); 
        if ($order->oid) {
            //清空數據
            Yii::app()->session->add('coin', 0);
            $payinfo = unserialize(Yii::app()->session->add('payinfo', ''));
            Yii::app()->shoppingCart->clear();
            
            //發送訂單確認信
            $title = '已接獲您的 Jowin!揪贏網 訂購單('.$order->oid.')通知函';
            $content = '親愛的 '.$user->realname.' 您好:<br /><br />
Jowin!揪贏網 已接獲您此次的訂購需求，在此感謝您對 Jowin!揪贏網 的支持。<br />
您此次的訂購單明細如下，若您對於訂購單內容有任何疑問，請您依據訂購單單號與「客服中心」聯繫，我們會盡速協助處理，謝謝您!<br />
訂單編號：'.$order->oid.'<br />
訂購時間：'.date('Y/m/d H:i:s',  strtotime($order->dateline)).'<br />
付款方式：'.Yii::app()->params['paytype'][$order->pay_type].'<br />
';
foreach ($order->items as $item) {
    $content.= '商品名稱 : '.$item->product->pname.' * '.$item->number.'<br />
';
} 
            $content.='<br />
To Jowin Member,<br />
This is a message from Jowin.com in Chinese Big5 code.<br />
We have received your online inquiry. If the Chinese text cannot be displayed properly, please go to https://myaccount.jowinwin.com to check your order status.<br /><br />

Thank You.<br /><br />

※貼心提醒 : <br />
1.	基於個人資料安全維護原則，我們不會於往來信件中顯示完整訂購/出貨明細，若您想要進一步查詢訂單明細，請至 Jowin!揪贏網 「會員專區」中之「查詢訂單」選項中查詢。<br />
2.	為保障會員權益，Jowin!揪贏網 保有決定是否接受訂單及出貨與否之權利。<br /><br />

Jowin!揪贏網團隊 敬上<br /><br />

____________________________________________________________________________________________<br />
Jowin!揪贏網 <br />
http://www.jowinwin.com

Jowin!揪贏網 Facebook粉絲團連結<br />
https://www.facebook.com/pages/Join-To-Win-%E6%8F%AA%E8%B4%8F%E7%B6%B2/137786092972951<br /><br />

客服中心連結 : www.jowinwin.com/service
';

            $result = $this->sentEmailSmtp($user->email, $title, $content);
            $order = Order::model()->findByPk($order->oid);
        }else{
            echo "<script>alert('下單失敗！');window.location.href='".Yii::app()->createUrl('shop/cart')."';</script>";
            exit;
        }
        $this->render('done', array(
            'row' => $order,
        ));
    }

    //購物金折抵
    public function actionCoinDiscount() {
        $this->check();
        $this->layout = 'pop';
        $user = User::model()->findByPk(Yii::app()->user->id);
        if (Yii::app()->request->isPostRequest) {
            $coin = (int) $_POST['coin'];
            if ($coin >= 0 && $coin <= $user->coin && $coin <= Yii::app()->shoppingCart->getDiscountCoin()) {
                Yii::app()->session->add('coin', $coin);
                $close = true;
                $this->redirect(array('pay'));
            }else{
                $this->redirect(array('cart'));
            }
        }
//        $this->render('coin', array(
//            'user' => $user,
//            'close' => $close,
//        ));
    }

    //核實購物金狀況是否合法
    protected function checkCoin() {
        $this->check();
        Helper::accounting(Yii::app()->user->id); //整理購物金情況
        $user = User::model()->findByPk(Yii::app()->user->id);
        //抵扣金為負數時自動清零，商品統計折扣少於規定下線，折扣金幣自動清零
        if (Yii::app()->session->get('coin') < 0 || Yii::app()->shoppingCart->getDiscountCoin() < Yii::app()->params['minDiscountCoin']) {
            Yii::app()->session->add('coin', 0);
        }
        header("Content-type:text/html;charset=utf-8");
        //購物金大於用戶餘額或者大於訂單允許的購物金抵扣上限時打回修改
        if (Yii::app()->session->get('coin') > $user->coin) {
            echo '<script>alert("您使用的抵扣金金額大於您帳戶的抵扣金餘額，請返回修改！");window.location.href="' . Yii::app()->createUrl('shop/cart') . '"</script>';
            exit;
        }
        if (Yii::app()->session->get('coin') > Yii::app()->shoppingCart->getDiscountCoin()) {
            echo '<script>alert("您使用的抵扣金金額大於訂單允許的購物金抵扣上限，請返回修改！");window.location.href="' . Yii::app()->createUrl('shop/cart') . '"</script>';
            exit;
        }
//        echo 
    }

    public function actionTest() {
        $product = Product::model()->findByPk(1);
        echo Yii::app()->shoppingCart->isEmpty();
    }
    
    //發送郵件類SMTP
    protected function sentEmailSmtp($to, $title, $content, $att = '') {
        set_time_limit(180);
        $message = new YiiMailMessage();

        $message->setContentType("text/html");
        $message->setTo(explode(',', $to));
        $message->setFrom(array(Yii::app()->params['systemEmail'] => 'join'));
        $message->setSubject($title);
        $message->setBody($content);

        $result['result'] = true;
        try {
            Yii::app()->mail->send($message);
        } catch (Swift_ConnectionException $e) {
            $result['result'] = false;
            $result['error'] = 'There was a problem communicating with SMTP: ' . $e->getMessage();
        }
        return $result;
    }

}